import time

import controller
import utils


def collect_master():
    topic = "collect_data"

    ips = controller.get_down_ip("master")
    if ips:
        for ip in ips:
            utils.send_to_redis_one(ip.rstrip("\n"), topic, "run_head")
        time.sleep(5)

        msgs = utils.get_from_redis("localhost", topic)

        for msg in msgs:
            print(msg)


def heart_beat():
    add_ips, red_ips = controller.check_down_ip("master", utils.check_redis_2("localhost"))
    if add_ips:
        for ip in add_ips:
            print(f"discover {ip}")
            controller.add_head_down([ip])
            utils.add_line("/collector_slave/config/log/log.txt", f"discover head: {ip}")
        utils.add_line("/collector_slave/config/log/log.txt", f"{time.time()}")
        utils.add_line("/collector_slave/config/log/log.txt", "")
    if red_ips:
        print("please check these nodes:")
        for ip in red_ips:
            print(ip)
            controller.delete_head_down([ip])
            utils.add_line("/collector_slave/config/log/log.txt", f"please check head: {ip}")
        utils.add_line("/collector_slave/config/log/log.txt", f"{time.time()}")
        utils.add_line("/collector_slave/config/log/log.txt", "")


def run_master():
    t = utils.RepeatingTimer(15.0, collect_master)
    h = utils.RepeatingTimer(20.0, heart_beat)
    t.start()
    h.start()
